package com.taiyuan.ty.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taiyuan.ty.common.BCryptPasswordEncoder;
import com.taiyuan.ty.common.R;
import com.taiyuan.ty.entity.Place;
import com.taiyuan.ty.entity.User;
import com.taiyuan.ty.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author : 周桓宇
 * @description : 用户登录
 * @createDate : 2025/3/25 下午10:48
 */
@RestController
@Slf4j
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<String> save(@RequestBody User user) {
        // 1.判断用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, user.getOpenid());
        User one = userService.getOne(queryWrapper);
        if (one != null) {
            return R.error("用户已存在");
        }
        // 2.注册用户
        userService.save(user);
        return R.success("注册成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        String openid = map.get("openid");
        if (openid != null) {
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openid));
            if (user != null) {
                session.setAttribute("user", user.getOpenid());
                return R.success(user);
            }
        }
        return R.error("登录失败");
    }

    /**
     * 用户修改
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody User user) {
        // 1.判断用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, user.getOpenid());
        User one = userService.getOne(queryWrapper);
        if (one != null) {
            userService.updateById(user);
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 用户列表
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        Page<User> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(User::getOpenid);

        userService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }
}